package meconsea.life.admin.web;


import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import meconsea.life.admin.accessor.AdminUserAccessor;
import meconsea.life.admin.accessor.AdminUserLogAccessor;
import meconsea.life.admin.entity.AdminUser;
import meconsea.life.admin.entity.AdminUserLog;
import meconsea.life.util.ComUtil;
import meconsea.life.util.Constant;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.google.inject.Inject;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class AdminLoginAct  extends ActionSupport {
	private final static Logger log = Logger.getLogger(AdminLoginAct.class);
	private String username;
	private String password;
	private String psnCard;
	private String action;
	private String msg;
	
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}
	@Inject
	private AdminUserAccessor adminUserAccessor;
	@Inject
	private AdminUserLogAccessor adminUserLogAccessor;
	
	public String getAction() {
		return action;
	}
	public void setAction(String action) {
		this.action = action;
	}
	public String execute(){
		if("login".equals(action)){
			AdminUser au = adminUserAccessor.getAdminUserByLoginName(getUsername());
			HttpServletRequest hsr = (HttpServletRequest)ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
			String reqAddr = hsr.getRemoteAddr();
			String reqHost = hsr.getRemoteHost();
			String currTime = ComUtil.getCurrTime();
			AdminUserLog aul = new AdminUserLog();
			if(au != null && au.getStatus() != 0){
				String _tpwd = ComUtil.md5(getUsername()+getPassword()+getPsnCard());
				if(au.getPassword().equals(_tpwd)){
					//put au to the session
					Map sessionMap = ActionContext.getContext().getSession(); 
					sessionMap.put(Constant.ADMIN_USER_SESSION, au);
					aul.setUserid(au.getId());
					aul.setLoginfo(au.getRealName()+"于"+currTime+"在"+reqAddr+"("+reqHost+")登陆系统成功.");
					this.adminUserLogAccessor.save(aul);
					return this.SUCCESS;
				}else{
					aul.setLoginfo(au.getRealName()+"于"+currTime+"在"+reqAddr+"("+reqHost+")登陆系统失败.");
					this.adminUserLogAccessor.save(aul);
					setMsg("登陆信息(密码或身份证号)错误！");
				}
			}else{
				setMsg("用户名不存在！");
			}
		}
		return this.ERROR;
	}
	public String login(){
		return "";
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getPsnCard() {
		return psnCard;
	}
	public void setPsnCard(String psnCard) {
		this.psnCard = psnCard;
	}
}
